import { Outlet, Link, useNavigate, json } from "react-router-dom";
import { Button, Input, message } from "antd";
import "./login.css";
import loginIcon from "../img/login/73329722893421062.png";
import { getUser2Djm } from "../api/api";
import { useState } from "react";

function Login() {
  const navigate = useNavigate();
  const [phone, setPhone] = useState(null);
  const [password, setPassword] = useState("");
  const [messageApi, contextHolder] = message.useMessage();
  const login = () => {
    getUser2Djm(phone).then((res) => {
      // console.log(res);
      if (res.msg == "查找成功") {
        if (res.data.password == password) {
          let token = Math.random().toString(36).slice(-10) + phone.slice(0, 6);
          sessionStorage.setItem("token", token);
          sessionStorage.setItem("user", res.data.phone);
          sessionStorage.setItem("id", res.data.id);
          sessionStorage.setItem("userName", res.data.userName);
          sessionStorage.setItem("touxi", JSON.stringify(res.data.img) );
          messageApi.open({
            type: "success",
            content: "登录成功",
          });
          navigate("/home");
        } else {
          messageApi.open({
            type: "error",
            content: "用户名或密码不正确",
          });
        }
      } else {
        messageApi.open({
          type: "error",
          content: "用户名不存在",
        });
      }
    });
  };
  return (
    <div className="login">
      {contextHolder}
      <div className="login-mar">
        <div className="login-header">
          <span
            onClick={() => {
              navigate("/register");
            }}
          >
            注册
          </span>
        </div>
        <div className="login-icon">
          <img src={loginIcon} alt="" />
        </div>
        <div className="login-font">WELCOME</div>
        <div className="login-ipt1">
          <Input
            value={phone}
            onChange={(e) => {
              setPhone(e.target.value);
            }}
            placeholder="请输入手机号"
          ></Input>
        </div>
        <div className="login-ipt2">
          <Input.Password
            value={password}
            onChange={(e) => {
              setPassword(e.target.value);
            }}
            placeholder="请输入密码"
          />
        </div>
        <div className="login-btn">
          <Button
            block
            style={{ background: "#e98f36", color: "#fff" }}
            onClick={() => login()}
          >
            登录
          </Button>
        </div>
        <div
          className="login-bottom"
          onClick={() => {
            navigate("/searchpwd");
          }}
        >
          忘记密码
        </div>
      </div>
    </div>
  );
}
export default Login;
